package com.turing.post.webservice.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.turing.post.common.util.NationCode;

public class CreateExcel {

	public static void main(String[] args) {
		try {
			exportExcel(RecordingOperationLog(new NationCode()));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("unchecked")
	public static List<String[]> RecordingOperationLog(Object obj) {
		// 所有属性
		Field[] fields = obj.getClass().getDeclaredFields();
		Class classType = obj.getClass();
		@SuppressWarnings("unused")
		String claName = classType.getName();
		String fieldName = null;
		List<String[]> list = new ArrayList<String[]>();
		String type = "";
		Field _field = null;
		// 反射获取值
		for (int i = 0; i < fields.length; i++) {
			_field = fields[i];
			fieldName = _field.getName();
			type = fields[i].getGenericType().toString();
			list.add(new String[] { fieldName,
							type.substring(6, type.length()) });
		}
		return list;
	}

	public static void exportExcel(List<String[]> list) throws IOException {
		// 声明一个工作薄
		HSSFWorkbook workbook = new HSSFWorkbook();
		String filePath = "D:\\test.xls";
		// 生成一个表格
		HSSFSheet sheet = workbook.createSheet("sheet1");
		// 设置表格默认列宽度为15个字节
		sheet.setDefaultColumnWidth(24);
		// 生成一个样式
		HSSFCellStyle style = workbook.createCellStyle();

		// 设置这些样式
		style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style.setBorderRight(HSSFCellStyle.BORDER_THIN);
		style.setBorderTop(HSSFCellStyle.BORDER_THIN);
		style.setAlignment(HSSFCellStyle.ALIGN_LEFT);

		// 第一行
		HSSFRow row1 = sheet.createRow(0);
		HSSFCell cell1 = row1.createCell(0);
		cell1.setCellValue("字段属性");
		cell1.setCellStyle(style);

		HSSFCell cell2 = row1.createCell(1);
		cell2.setCellValue("字段类型");
		cell2.setCellStyle(style);

		HSSFCell cell3 = row1.createCell(2);
		cell3.setCellValue("描述");
		cell3.setCellStyle(style);

		// 产生表格标题行
		HSSFRow row = null;
		for (int i = 0; i < list.size(); i++) {
			row = sheet.createRow(i + 1);
			// 产生单元格
			HSSFCell cell = row.createCell(0);
			cell.setCellStyle(style);
			cell.setCellValue(list.get(i)[0]);

			// 产生单元格
			cell = row.createCell(1);
			cell.setCellStyle(style);
			cell.setCellValue(list.get(i)[1]);

			// 产生单元格
			cell = row.createCell(2);
			cell.setCellStyle(style);
			cell.setCellValue("");
		}

		FileOutputStream out = null;
		out = new FileOutputStream(new File(filePath));
		workbook.write(out);
		out.flush();
		out.close();
	}
}